package com.sgcc.pda.mdrh.zoom.plugin;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;

import com.qihoo360.replugin.RePlugin;
import com.qihoo360.replugin.model.PluginInfo;
import com.sgcc.pda.baselibrary.utils.ActivityCheckUtil;
import com.sgcc.pda.baselibrary.utils.LogUtil;
import com.sgcc.pda.sdk.utils.DialogUtil;
import com.sgcc.pda.sdk.utils.dialog.DialogLoadingFMV4;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;

/**
 * 插件安装异步执行任务
 *
 * @author Ben
 * @version 2019.08.29
 */
public class PluginAsyncTask extends AsyncTask<String, String, String> {

    public static final String FILE_SAVE_PATH = "/safeControl/";

    private final WeakReference<Context> weakReference;
    private DialogLoadingFMV4 loadingFMV4;
    private ResultListener listener;
    private String path;
    private boolean isAsset;// 是否assets文件夹

    private PluginAsyncTask(Context context) {
        weakReference = new WeakReference<>(context);
    }

    @Override
    protected void onPreExecute() {
        // 显示弹窗
        Context context = weakReference.get();
        loadingFMV4 = DialogUtil.getProgressDialogV4(context, "正在安装，请稍后...");
        loadingFMV4.setCancelable(false);
        DialogUtil.show(context, loadingFMV4);
    }

    @Override
    protected String doInBackground(String... values) {
        Context context = weakReference.get();
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        if (!ActivityCheckUtil.isActive(context)) {
            return null;
        }

        if (isAsset) {
            path = copyAssets(context, path);
        }
        PluginInfo pluginInfo = RePlugin.install(path);
        if (pluginInfo != null) {
            // 预加载插件
            if (RePlugin.preload(pluginInfo)) {
                return pluginInfo.getName();
            }
        }
        return null;
    }


    @Override
    protected void onPostExecute(String value) {
        if (listener != null) {
            listener.onFinish(value);
        }
        Context context = weakReference.get();
        // 取消弹窗
        DialogUtil.dismiss(context, loadingFMV4);
    }

    /**
     * 安装插件
     *
     * @param path 插件路径
     */
    public static void installPlugin(Context context, String path, ResultListener listener) {
        PluginAsyncTask task = new PluginAsyncTask(context);
        task.setPath(path);
        task.setAsset(false);
        task.setListener(listener);
        task.execute();
    }

    /**
     * 安装Assets插件
     *
     * @param path assets路径
     */
    public static void installAssets(Context context, String path, ResultListener listener) {
        PluginAsyncTask task = new PluginAsyncTask(context);
        task.setPath(path);
        task.setAsset(true);
        task.setListener(listener);
        task.execute();
    }

    /**
     * 文件路径
     *
     * @param path
     */
    private void setPath(String path) {
        this.path = path;
    }

    /**
     * 是否是Assets路径
     *
     * @param isAsset
     */
    private void setAsset(boolean isAsset) {
        this.isAsset = isAsset;
    }

    /**
     * 结果监听
     *
     * @param listener
     */
    private void setListener(ResultListener listener) {
        this.listener = listener;
    }

    public interface ResultListener {
        /**
         * 安装完成
         *
         * @param name 插件名称(别名或包名), null是安装失败
         */
        void onFinish(String name);
    }


    /**
     * 拷贝assets内的文件拷贝到外置存储
     *
     * @param path assets路径
     * @return 文件路径
     */
    private String copyAssets(Context context, String path)  {
        // 定义拷贝到外置存储plugin文件夹
        File file = new File(Environment.getExternalStorageDirectory() + FILE_SAVE_PATH + path);
        // 创建文件
        if (file.exists()) {
            file.delete();
        } else {
            file.getParentFile().mkdirs();
        }
        InputStream is=null;
        FileOutputStream fos=null;
        try {
            // 读取assets文件
            is = context.getAssets().open(path);
            // 文件输出流
            fos = new FileOutputStream(file);
            file.createNewFile();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) > 0) {
                fos.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos!=null){
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        LogUtil.e(":" + file.getPath());
        return file.getPath();
    }

}
